package com.xyhy.starter.mfx.listener;

import com.mybatisflex.annotation.InsertListener;
import com.xyhy.core.utils.id.IdUtil;
import com.xyhy.core.utils.spring.SpringContextUtil;
import com.xyhy.starter.mfx.entity.MfxObject;
import com.xyhy.starter.mfx.entity.MfxType;

import java.time.LocalDateTime;
import java.util.Objects;

public class MfxObjectInsertListener implements InsertListener {
  @Override
  public void onInsert(Object entity) {
    handleMfxObject(entity);
    handleMfxType(entity);
  }


  private void handleMfxObject(Object entity) {
    if (!(entity instanceof MfxObject)) return;

    MfxObject object = (MfxObject) entity;
    if (Objects.isNull(object.getId())) {
      object.setId(IdUtil.getId());
    }

    LocalDateTime now = LocalDateTime.now();
    Long userId = SpringContextUtil.getUserId();
    object.setCreateBy(userId);
    object.setCreateTime(now);
    object.setUpdateBy(userId);
    object.setUpdateTime(now);
  }

  private void handleMfxType(Object entity) {
    if (!(entity instanceof MfxType)) return;
    MfxType object = (MfxType) entity;

    LocalDateTime now = LocalDateTime.now();
    Long userId = SpringContextUtil.getUserId();
    object.setCreateBy(userId);
    object.setCreateTime(now);
    object.setUpdateBy(userId);
    object.setUpdateTime(now);
  }

}
